package main

import (
	"fmt"
	"sort"
)

/*slice 排序示例*/
type Person1 struct {
	Age uint32
}

type PersonSlice []*Person1

func (s PersonSlice) Len() int           { return len(s) }
func (s PersonSlice) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s PersonSlice) Less(i, j int) bool { return s[i].Age < s[j].Age }
func SortPerson(s PersonSlice) {
	sort.Sort(s)
}

// 结构体排序
func SortStruct() {
	persons := PersonSlice{
		&Person1{
			Age: 1,
		},
		&Person1{
			Age: 5,
		},
		&Person1{
			Age: 9,
		},
		&Person1{
			Age: 7,
		},
		&Person1{
			Age: 4,
		},
	}

	SortPerson(persons)
	for k := range persons {
		fmt.Println(persons[k].Age)
	}
	// fmt.Printf("after sort:%+v", persons)
}

type Int32List []int

func (s Int32List) Len() int           { return len(s) }
func (s Int32List) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s Int32List) Less(i, j int) bool { return s[i] < s[j] }
func SortSliceDemo(slice Int32List) {
	sort.Sort(slice)
}

// 数组排序
func SortSlice() {
	a := []int{1, 8, 9, 4, 5, 6}
	SortSliceDemo(Int32List(a))
	fmt.Println(a)
}

func main() {
	SortStruct()
	SortSlice()
}
